import React, { useCallback, useState } from 'react';
import { Button, Card, Col, Descriptions, Modal, Row, Space, Steps, Table, Tag, message,Form, DatePicker, Input, Select, Upload, } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { FileTextOutlined, UnorderedListOutlined, UploadOutlined } from '@ant-design/icons';
import ActivityForm from '@/pages/activityInfoTeacher/activityDetails/activityForm';
import { Pie } from '@ant-design/plots';
import { Calendar } from 'antd';
import { ProColumns } from '@ant-design/pro-components';
import { useEffect } from 'react';
import JSZip from 'jszip';
import FileSaver from 'file-saver'
import ExportJsonExcel from "js-export-excel";
import axios from 'axios';
import {
  getdetail,
  getStuFeedBackInfo, getStuJoinList,
  getSubActivityList,
  setActivityPulished,
} from '@/services/activityInfo';
import {
  createSub
} from '@/services/fileService'
import { ColumnsType } from '_antd@4.24.12@antd/es/table';
import { Link, useLocation, history } from 'umi';
const { Option } = Select;
const { TextArea } = Input;
export type TableListItem = {
  key: number;
  stuName: string;
  stuCode: string;
  majorLabel: string;
  classLabel: string;
  isJoin: string
};
const countStyle = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  textAlign: 'justify',
  color: 'black',
  fontSize: '30px',
  fontWeight: 'bold',
};
const statusMap = [
  {
    color: 'green',
    text: '已打卡',
  },
  {
    color: 'red',
    text: '未打卡',
  },
];
export type Status = {
  color: string;
  text: string;
};
const ActivityDetails: React.FC = () => {
  const stuJoinListColumns: ProColumns<TableListItem>[] = [
    {
      title: '姓名',
      width: 200,
      align: 'left',
      dataIndex: 'stuName',
      render: (text, record) => {
        return <Link to={"/StudentMessage/StudentInfoDetail?stuCode=" + record.stuCode}>{text}</Link>
      }
    },
    {
      title: '学号',
      width: 200,
      align: 'left',
      dataIndex: 'stuCode',
    },
    {
      title: '专业',
      width: 200,
      align: 'left',
      dataIndex: 'majorLabel',
    },
    {
      title: '班级',
      width: 200,
      dataIndex: 'classLabel',
    },
    {
      title: '是否打卡',
      width: 200,
      dataIndex: 'status',
      render: (_, record) => <Tag color={record.status?.color}>{record.status?.text}</Tag>,
    },
  ];
  const subActivityTableColumns: ColumnsType<any> = [
    {
      title: '活动名称',
      dataIndex: 'activityLabel',
      key: 'activityLabel',
      width: '20%',
      render: (text, record: any) => {
        return (
          <a
            onClick={() => {
              history.push(`/activityInfoTeacher/activityDetails?activityId=${record.id}`)
              window.location.reload()
            }}>
            {text}
          </a>
        )
      }
    },
    {
      title: '举办方',
      dataIndex: 'organizationalUnit',
      key: 'organizationalUnit',
      width: '20%',
    },
    {
      title: '举办地点',
      dataIndex: 'activityAddress',
      key: 'activityAddress',
      width: '20%',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: '20%',
      render: (startTime: string) => {
        const date = new Date(startTime);
        return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: '20%',
      render: (endTime: string) => {
        const date = new Date(endTime);
        return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
      },
    },
  ];
  const feedBackColumns = [
    {
      title: '姓名',
      dataIndex: 'stuName',
      width: '10%',
      render: (text, record) => {
        return <Link to={"/StudentMessage/StudentInfoDetail?stuCode=" + record.stuCode}>{text}</Link>
      }
    },
    {
      title: '学号',
      dataIndex: 'stuCode',
      width: '10%'
    },
    {
      title: '专业',
      dataIndex: 'majorLabel',
      width: '10%'
    },
    {
      title: '班级',
      dataIndex: 'classLabel',
      width: '10%'
    },
    {
      title: '感想',
      dataIndex: 'activityImpression',
      render: (text: any) => {
        return (
          <div dangerouslySetInnerHTML={{ __html: text }} />
        )
      },
      ellipsis: true,
      width: '10%'
    },
    {
      title: '对活动打分',
      dataIndex: 'studentRating',
      width: '10%'
    },
    // {
    //   title: '附件',
    //   dataIndex: 'fileId',
    //   render: (_: any, record: any) => (
    //     <Space size="middle">
    //       <Button type="primary" onClick={() => getDownLoad(record.fileId)}>
    //         附件下载
    //       </Button>
    //     </Space>
    //   ),
    //   width: '10%'
    // },
  ];
  function strToHtm1(str: any) {
    var div = document.createElement('div'); div.innerHTML = str;
    console.log(div.firstChild)
    return div.firstChild;
  }
  const { Step } = Steps;
  //基本数据
  const [activityDetails, setActivityDetails] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [progressBarNum, setProgressBarNum] = useState(1);
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const activityId = queryParams.get('activityId');
  //饼状图数据
  const [isAttendance, setIsAttendance] = useState<any[]>([0, 0]);
  const [feedIsAttendance, setFeedIsAttendance] = useState<any[]>([0, 0]);
  const [activeStatus, setActiveStatus] = useState<string>();
  const data = [
    {
      type: '未打卡',
      value: isAttendance[0],
    },
    {
      type: '已打卡',
      value: isAttendance[1],
    }
  ];
  const config = {
    appendPadding: 0,
    data,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.6,
    label: {
      type: 'inner',
      offset: '-50%',
      content: '{value}',
      style: {
        textAlign: 'center',
        fontSize: 14,
      },
    },
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
    ],
    statistic: {

    },
  };
  const feedBackData = [
    {
      type: '未反馈',
      value: feedIsAttendance[0],
    },
    {
      type: '已反馈',
      value: feedIsAttendance[1],
    }
  ];
  const feedBackDataConfig = {
    appendPadding: 0,
    data: feedBackData,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.6,
    label: {
      type: 'inner',
      offset: '-50%',
      content: '{value}',
      style: {
        textAlign: 'center',
        fontSize: 14,
      },
    },
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
    ],
    statistic: {

    },
  };
  // 表格数据
  const [stuJoinList, setStuJoinList] = useState<any>();
  const [subActivityTableData, setSubActivityTableData] = useState<any[]>();
  const [feedBackTabelData, setFeedBackTabelData] = useState<any[]>([]);
  //创建子活动
  const [modalVisible, setModalVisible] = useState(false);//控制 Modal 的显示与隐藏：
  const [form] = Form.useForm();//表单对象
  const [fileList, setFileList] = useState([]);
  /*
数据处理
--------------------------------------------------------------------------------------------------
 */
  // 处理进度条
  const progressBar = (value: any) => {
    if (value) {
      const registrationDeadline = new Date(value.registrationDeadline)
      const startTime = new Date(value.startTime)
      const endTime = new Date(value.endTime)
      const currentTime = new Date()
      if (currentTime > registrationDeadline) setProgressBarNum(2)
      else if (currentTime > endTime) setProgressBarNum(3)
    }
  }
  //单个文件下载
  const getDownLoad = (value: any) => {
    if (value) {
      message.warn("文件列表为空")
      return
    }
    window.open("/api/freshSystem/downloadFile/" + value)
  }
  // 请求文件资源
  const getFile = useCallback((value: string) => {
    let url = "/api/freshSystem/downloadFile/" + value
    console.log(url)
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        responseType: 'blob',
      }).then((data) => {
        console.log(data)
        resolve(data);
      }).catch((error) => {
        reject(error.toString());
      });

    });
  }, []);

  // 批量下载
  const patchDownload = (value: any) => {
    console.log(value)
    const zip = new JSZip();
    const imgsss: JSZip | null = zip.folder('批量下载');
    const promises: Promise<any>[] = [];
    value.forEach((item) => {
      const promise = getFile(item.fileId).then((data: any) => {
        // 下载文件, 文件名
        const file_name = decodeURIComponent(data.headers.get("content-disposition").split('filename=')[1].replace(/"/g, ''));
        // 逐个添加文件
        imgsss?.file(file_name, data.data, { binary: true });

      });
      promises.push(promise);
    });
    Promise.all(promises).then(() => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // 生成二进制流,利用file-saver保存文件
        FileSaver.saveAs(content, '批量下载.zip');
      }).catch(() => {
        // 如果有资源文件下载失败，就直接用a链接下载
        message.error("压缩文件下载失败")
        // value.forEach((item) => {
        //     File.download({ url: "/api/freshSystem/downloadFile/" + item.fileId, fileName: item.name });
        // });
      });

    });
  }
  const handleExportCurrentExcel = (ExcelData: any) => { //ExcelData为后端返回的data数组
    let sheetFilter = ["stuName", "stuCode", "majorLabel", "classLabel", "activityImpression", "studentRating"];
    let option = {
      fileName: '',
      datas: {
      },
    };
    option.fileName = '活动反馈';
    option.datas = [
      {
        sheetData: ExcelData,
        sheetName: '活动反馈',
        sheetFilter: sheetFilter,
        sheetHeader: ['姓名', '学号', '专业', '班级', '感谢', '对活动打分'],
        columnWidths: [5, 5, 10, 10, 15, 5]
      },
    ];
    var toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  }
  // 计算打卡人数和未打卡人数
  function countAttendance(arr: any) {
    let count0 = 0;
    let count1 = 0;
    for (const item of arr) {
      if (item.isAttendance === "0") {
        count0++;
      } else if (item.isAttendance === "1") {
        count1++;
      }
    }
    return [count0, count1]
  }
  const Published = async () => {
    try {
      const response = await setActivityPulished(activityDetails.id);
      if (response?.code === '200') {
        // 在这里根据响应进行判断，执行相应的逻辑
        message.success('发布成功');
        window.location.reload();
      } else {
        message.error('发布失败');
      }
    } catch (error) {
      console.error('API error:', error);
    }
  };
  const handleNewActivityClick = () => {
    setModalVisible(true);
  };
    const handleModalOk = () => {
    // 处理表单提交逻辑
    const formValues = form.getFieldsValue();
    formValues.startTime = formValues.startTime.format('YYYY-MM-DD HH:mm:ss');
    formValues.endTime = formValues.endTime.format('YYYY-MM-DD HH:mm:ss');

    formValues.teaName = window.localStorage.userName;
    formValues.teaCode = window.localStorage.userAccount;
    console.log(formValues); // 这里打印整个表单的值对象

    const formData = new FormData();
    formData.append('activityAddress', formValues.activityAddress);
    formData.append('activityCategory', formValues.activityCategory);
    formData.append('activityContent', formValues.activityContent);
    formData.append('activityLabel', formValues.activityLabel);
    formData.append('activityLevel', formValues.activityLevel);
    formData.append('activityObjective', formValues.activityObjective);
    formData.append('endTime', formValues.endTime);
    formData.append('guest', formValues.guest);
    formData.append('guestTitle', formValues.guestTitle);
    formData.append('isPublished', formValues.isPublished);
    formData.append('needApproval', formValues.needApproval);
    formData.append('needFile', formValues.needFile);
    formData.append('organizationalUnit', formValues.organizationalUnit);
    formData.append('startTime', formValues.startTime);
    formData.append('teaCode', formValues.teaCode);
    formData.append('teaName', formValues.teaName);
    formData.append('parentsId', activityDetails.id);
    if (fileList.length != 0 && fileList){
      for (let i = 0; i < fileList.length; i++) {
        formData.append('upload', fileList[i].originFileObj);
      }
    }
    for (const pair of formData.entries()) {
      console.log(pair[0] + ": " + pair[1]);
    }
    createSub('',formData).then((res: any)=>{
      if (res.code == '200'){
        message.success("创建成功")
        window.location.reload();
      }
      else message.error("创建失败")
    })
    setModalVisible(false);
  };
  const handleModalCancel = () => {
    setModalVisible(false);
  };

  /*
  --------------------------------------------------------------------------------------------------
  数据处理
 */
  /*
  数据请求
  --------------------------------------------------------------------------------------------------
   */
  useEffect(() => {
    getdetail(activityId).then((response: any) => {//活动详情
      if (response.result) {
        setActiveStatus(response.result.isPublished)
        // console.log(response.result)
        setActivityDetails(response.result)
        progressBar(response?.result)

      }
    })
    getSubActivityList(activityId).then((response: any) => {//活动计划
      if (response.result)
        setSubActivityTableData(response.result)
      // console.log(response.result)
    })
    getStuFeedBackInfo(activityId).then((response: any) => {//活动反馈
      if (response.result) {
        setFeedIsAttendance(countAttendance(response.result))
        setFeedBackTabelData(response.result)
      }
    })
    getStuJoinList(activityId).then((response: any) => {//人员详情
      if (response.result) {
        // console.log(response.result);
        response.result.forEach(item => {
          if (item.isAttendance === '1' || item.isAttendance === 1) {
            item.status = statusMap[1]
          } else {
            item.status = statusMap[0]
          }
        })
        setIsAttendance(countAttendance(response.result))
        setStuJoinList(response.result)
      }
    })
  }, []); // 空依赖数组确保该 effect 仅在组件挂载时执行一次
  /*
  --------------------------------------------------------------------------------------------------
  数据请求
   */

  return (
    <PageContainer>
      <Modal title="参与成员" width={"50%"} open={isModalOpen} footer={null} onCancel={() => setIsModalOpen(false)}>
        <ProTable<TableListItem>
          columns={stuJoinListColumns}
          dataSource={stuJoinList}
          pagination={{ pageSize: 10 }}
          size={'small'}
          search={false}
          rowKey="key"
        />
      </Modal>
      <Modal title="活动反馈" width="50%" open={isFormModalOpen} footer={null} onCancel={() => setIsFormModalOpen(false)}>
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Space>
            <Button type="primary" onClick={() => handleExportCurrentExcel(feedBackTabelData)}>
              下载列表
            </Button>
            <Button type="primary" onClick={() => patchDownload(feedBackTabelData)}>
              下载全部附件
            </Button>
          </Space>
          <div>
            <Table columns={feedBackColumns} dataSource={feedBackTabelData} size="small" />
          </div>
        </Space>
      </Modal>
      <ProCard style={{ marginBottom: 24 }}>
        <Descriptions title={<div><span>活动进度</span>&nbsp;&nbsp;<span></span></div>}>
        </Descriptions>
        {/** 活动当天为活动进行中 **/}
        <Steps progressDot current={progressBarNum}>
          <Step title={<span style={{ fontSize: 14 }}>发布活动</span>} />
          <Step title={<span style={{ fontSize: 14 }}>报名中</span>} />
          <Step title={<span style={{ fontSize: 14 }}>进行中</span>} />
          <Step title={<span style={{ fontSize: 14 }}>圆满结束！</span>} />
        </Steps>
      </ProCard>
      <Row gutter={24}>
        <Col xl={18} lg={24} md={24} sm={24} xs={24} >
          <Card title={<span style={{ marginBottom: 24 }}> <FileTextOutlined /> <b>活动详情</b> </span>}>
            <ActivityForm activityId={activityId} />
          </Card>
          <Card
            title={<span > <UnorderedListOutlined /> <b>活动计划</b> </span>}
            extra={
              <Button type="primary" onClick={handleNewActivityClick}>
                创建子活动
              </Button>
            }
            >
            <Table
              columns={subActivityTableColumns}
              rowKey="id"
              dataSource={subActivityTableData}
            />
          </Card>
          <Modal
        title="创建新活动"
        visible={modalVisible}
        onCancel={handleModalCancel}
        onOk={handleModalOk}
      >
        <Form form={form}>
          {/* activityLabel */}
          <Form.Item label="活动名称" name="activityLabel" rules={[{ required: true, message: '请输入活动名称' }]}>
            <Input />
          </Form.Item>
          {/* 活动内容 */}
          <Form.Item label="活动内容" name="activityContent" rules={[{ required: true, message: '请输入活动内容' }]}>
            <TextArea />
          </Form.Item>
          {/* 活动开始时间 */}
          <Form.Item label="活动开始时间" name="startTime" rules={[{ required: true, message: '请选择活动开始时间' }]}>
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          {/* 活动截止时间 */}
          <Form.Item label="活动截止时间" name="endTime" rules={[{ required: true, message: '请选择活动截止时间' }]}>
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          {/* 活动地点 */}
          <Form.Item label="活动地点" name="activityAddress" rules={[{ required: true, message: '请输入活动地点' }]}>
            <Input />
          </Form.Item>
          {/* 活动等级 */}
          <Form.Item label="活动等级" name="activityLevel" rules={[{ required: true, message: '请选择活动级别' }]}>
            <Select>
              <Option value="0">国家级</Option>
              <Option value="1">省级</Option>
              <Option value="2">校级</Option>
              <Option value="3">院级</Option>
            </Select>
          </Form.Item>
          {/* 活动培养类别 */}
          <Form.Item label="活动培养类别" name="activityCategory" rules={[{ required: true, message: '请选择活动培养类别' }]}>
            <Select>
              <Option value="0">活动竞赛</Option>
              <Option value="1">评奖评优</Option>
              <Option value="2">学生组织</Option>
            </Select>
          </Form.Item>
          {/* 活动培养目标 */}
          <Form.Item label="活动培养目标" name="activityObjective" rules={[{ required: true, message: '请选择活动培养目标' }]}>
            <Select>
              <Option value="0">理想信念</Option>
              <Option value="1">文化艺术</Option>
              <Option value="2">社会工作</Option>
              <Option value="3">实践服务</Option>
              <Option value="4">学术科技</Option>
              <Option value="5">体育素质</Option>
            </Select>
          </Form.Item>
          {/* 组织方 */}
          <Form.Item label="组织方" name="organizationalUnit" rules={[{ required: true, message: '请输入组织方' }]}>
            <Input />
          </Form.Item>
          {/* 是否公开 */}
          <Form.Item label="是否发布" name="isPublished" rules={[{ required: true, message: '请选择是否公开' }]}>
            <Select>
              <Option value="1">是</Option>
              <Option value="0">否</Option>
            </Select>
          </Form.Item>
          {/* 是否需要上传附件 */}
          <Form.Item label="是否需要上传附件" name="needFile" rules={[{ required: true, message: '请选择是否需要上传附件' }]}>
            <Select>
              <Option value="1">是</Option>
              <Option value="0">否</Option>
            </Select>
          </Form.Item>
          {/* 是否需要审批 */}
          <Form.Item label="报名是否需要审批" name="needApproval" rules={[{ required: true, message: '请选择是否需要审批' }]}>
            <Select>
              <Option value="1">是</Option>
              <Option value="0">否</Option>
            </Select>
          </Form.Item>
          {/* 嘉宾姓名 */}
          <Form.Item label="嘉宾姓名" name="guest">
            <Input />
          </Form.Item>
          {/* 嘉宾头衔 */}
          <Form.Item label="嘉宾头衔" name="guestTitle">
            <Input />
          </Form.Item>
          {/* 上传附件按钮 */}
          <Form.Item label="上传附件" name="upload">
            <Upload
              beforeUpload={()=>(false)}
              fileList={fileList}
              onChange={({ fileList: newFileList }) => setFileList(newFileList)}
            >
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
        </Col>
        <Col xl={6} lg={24} md={24} sm={24} xs={24}>
          <Card style={{ marginBottom: 24 }}>
          <Card bodyStyle={{ padding: 0 }} style={{ marginBottom: 24 }}>
            <Button
              style={{ width: "100%", height: 96 }}
              type="primary" size='large'
              disabled={activeStatus === '1'}
              onClick={() => Published()}
            >
              <div style={countStyle}>{activeStatus=='1'?'已发布':'发布'}</div>
            </Button>
          </Card>
            <div style={{ width: "100%" }}>
              <Calendar fullscreen={false} />
            </div>
          </Card>
          <Card style={{ marginBottom: 24, height: '350px' }} title="参与人员" extra={<a onClick={() => setIsModalOpen(true)}>人员详情</a>}>
            <Pie {...config} padding={[0, 50, 250, 10]} />
          </Card>
          <Card style={{ marginBottom: 24, height: '350px' }} title="活动反馈" extra={<a onClick={() => setIsFormModalOpen(true)}>反馈详情</a>}>
            <Pie {...feedBackDataConfig} padding={[0, 50, 250, 10]} />
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default ActivityDetails;
